import Wx, {wx} from "./Wx";

class UserInfoButtonHelper {
    private button: any = null;
    private isLandscape: boolean = false;
    private isShown: boolean = false;

    public setLandscape(land: boolean) {
        this.isLandscape = land;
    }

    // 显示用户信息button.
    public show(callback: (userInfo) => void, attachedNode?: cc.Node) {
        if (!Wx.isWeChatEnv()) {
            return;
        }
        this.hide();
        if (this.isShown) {
            cc.log("本次运行已经显示过,不再显示.");
            return;
        }
        let p = {x: 0, y: 0, width: cc.winSize.width, height: cc.winSize.height};
        if (attachedNode) {
            p = attachedNode.getBoundingBoxToWorld();
            if (this.isLandscape || true) {
                p.y = cc.winSize.height - p.y - p.height;
            }
        }
        let rect = Wx.realSize2Wx(p);
        cc.log("授权按钮尺寸:", p, rect);
        this.button = wx.createUserInfoButton({
            type: "text",
            text: "",
            withCredentials: false,
            style: {
                left: rect.x, top: rect.y,
                width: rect.width,
                height: rect.height,
                // backgroundColor: "#ff0000"
            }
        });
        this.button.onTap((res) => {
            cc.log(res);
            if (callback) {
                callback(res.userInfo);
            }
            // 点击过才算展示过.
            this.isShown = true;
            this.button.destroy();
            this.button = null;
        });
        this.button.show();
    }

    public hide() {
        if (this.button) {
            this.button.destroy();
        }
        this.button = null;
    }

    // 需要显示时,resole()
    public needShow(): Promise<any> {
        // 未授权时需要显示.
        return Wx.isScopeAuthed("scope.userInfo").then((ret) => {
            return Promise.resolve(!!ret);
        });
    }
}

export const userInfoButton: UserInfoButtonHelper = new UserInfoButtonHelper();